package com.example.homework9;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.room.DatabaseConfiguration;
import androidx.room.InvalidationTracker;
import androidx.sqlite.db.SupportSQLiteOpenHelper;

import com.example.homework9.sqliteroom.MyRoomDatabase;
import com.example.homework9.sqliteroom.User;
import com.example.homework9.sqliteroom.UserDao;

import java.util.List;

public class Fragment3_2 extends Fragment {
    private Button button1,button2;
    private TextView nameTextView, ageTextView, contentTextView;
    private String username;
    private int age;

    public Fragment3_2(){
        super(R.layout.fragment3_2);
    }

    public void onViewCreated(View view, Bundle savedInstanceState){
        super.onViewCreated(view,savedInstanceState);

        nameTextView = getView().findViewById(R.id.name);
        ageTextView = getView().findViewById(R.id.age);
        contentTextView = getView().findViewById(R.id.contentTextView);

        button1 = getView().findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                username = nameTextView.getText().toString();
                age = Integer.parseInt(ageTextView.getText().toString());

                MyRoomDatabase db = MyRoomDatabase.getInstance(getActivity());
                User user = new User();
                user.username = username;
                user.age = age;
                db.userDao().insert(user);

                showUsers(db.userDao().getAll());
            }
        });

        button2 = getView().findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                MyRoomDatabase db = MyRoomDatabase.getInstance(getActivity());
                db = MyRoomDatabase.getInstance(getActivity());
                showUsers(db.userDao().searchUsersByAge(18));
            }
        });

    }

    private void showUsers(List<User> users){
        StringBuilder stringBuilder = new StringBuilder();
        for(User user:users) {
            stringBuilder.append("id: ").append(user.id)
                    .append("  username: ").append(user.username)
                    .append("  age: ").append(user.age)
                    .append("\n");
        }
        contentTextView.setText(stringBuilder.toString());
    }
}